package com.gjs.common.manager;

import com.gjs.common.exception.BizException;
import com.gjs.common.manager.response.RspBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class BaseExceptionHandler {

	/**
	 * 处理其他异常
	 * @param e Exception
	 * @return RspBody
	 */
	@ExceptionHandler(Exception.class)
	public RspBody exceptionHandler(Exception e){
		log.error("发生异常！");
		log.error(e.getMessage());
		return RspBody.error(e.getMessage());
	}

    /**
     * 处理业务异常
	 * @param e BizException
	 * @return RspBody
     */
    @ExceptionHandler(BizException.class)
	public RspBody bizExceptionHandler(BizException e){
		return RspBody.error(e.getErr(),e.getMsg());
	}

	/**
	 * 参数校验异常
	 * @param ex BindException
	 * @return RspBody
	 */
	@ExceptionHandler(value = BindException.class)
	public RspBody handleBindException(BindException ex){
		List<String> defaultMsg = ex.getBindingResult().getAllErrors()
				.stream()
				.map(ObjectError::getDefaultMessage)
				.collect(Collectors.toList());
		return RspBody.error(defaultMsg.get(0));
	}
}